package cn.tedu.egcar1.controller;



import cn.tedu.egcar1.base.response.JsonResult;
import cn.tedu.egcar1.base.response.StatusCode;
import cn.tedu.egcar1.mapper.UserMapper;
import cn.tedu.egcar1.pojo.dto.UserLoginParam;
import cn.tedu.egcar1.pojo.dto.UserRegParam;
import cn.tedu.egcar1.pojo.entiy.User;
import cn.tedu.egcar1.pojo.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/v1/user/")
@Slf4j
@Tag(name = "01-用户管理接口")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    @Operation(summary = "用户注册接口")
    public JsonResult regInsertUser(@RequestBody UserRegParam userRegParam){
        log.debug("传入的参数："+userRegParam);
        String username = userRegParam.getUsername();
        int count =userMapper.selectUserByUsername(username);
        if(count>0){
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        log.debug("插入数据库的用户信息："+user);
        int row =userMapper.insertUser(user);
        if(row>0){
            return JsonResult.ok("用户注册成功！");
        }
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @PostMapping("login")
    @Operation(summary = "用户登录接口")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam){
        log.debug("传入的参数："+userLoginParam);
        UserVO userVO =userMapper.selectUserByUsernameAndPassword(userLoginParam);
        log.debug("查找到的数据："+ userVO);
        if(userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        BeanUtils.copyProperties(userLoginParam,userVO);
        log.debug("返回的用户信息："+userVO);
        return JsonResult.ok(userVO);
    }

}
